
function isIP(ip) {
    var re = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/
    return re.test(ip);
}


//生成随机字符串
function randomString(len) {
    len = len || 16;
    let chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
    let pwd = '';
    for (let i = 0; i < len; i++) {
        pwd += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    return pwd;
};


function addNew() {

    $("#labelName").val("");
    $("#labelMac").val("");
    $("#labelIP").val("");
    $('#addNew').modal('show');
}

function createList(pageNo = 1, pageSize = 10) {
    let matchData = {};
    let name = $("#txtSearch").val();
    if (name) {
        matchData.name = { $regex: name }
    }

    var start = (pageNo - 1) * pageSize;
    apiAdminGetRecord("limitIPModel", start, pageSize, matchData, function (data) {
        if (data.code === 0) {
            setTimeout(() => {
                $('#robotData').bootstrapTable('load', data.msg);
            }, 200)

        }
    });
}




function saveData() {

    let labelName = $("#labelName").val();
    if (!labelName || labelName.length === 0) {
        Swal.fire('请输入名称')
        return;
    }

    let labelIP = $("#labelIP").val();

    if (!isIP(labelIP)) {
        Swal.fire('请输入正确的IP地址')
        return;
    }

    let saveData = { name: labelName, ip: labelIP, createTime: Date.now() };
    apiAdminAddRecord('limitIPModel', saveData, () => {
        var currentPage = $('#robotData').bootstrapTable('getOptions').pageNumber
        createList(currentPage);
        $.modal({ body: '保存成功' });
        $('#addNew').modal('hide');
    });

}




function deleteData(key) {


    Swal.fire({
        title: '确定删除？',
        // text: "联盟删除后无法恢复，请谨慎操作",
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#198754',
        cancelButtonColor: '#d93444',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
    }).then((result) => {
        if (result.isConfirmed) {
            apiAdminDeleteRecord('limitIPModel', { '_id': key }, () => {
                var currentPage = $('#robotData').bootstrapTable('getOptions').pageNumber
                createList(currentPage);
                $.modal({ body: '删除成功' });
            });
        }
    });


}

function updateData(code, type, isStoped) {


    Swal.fire({
        title: '确定修改限制权限？',
        // text: "联盟删除后无法恢复，请谨慎操作",
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#198754',
        cancelButtonColor: '#d93444',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
    }).then((result) => {
        if (result.isConfirmed) {

            let updateStr = null;
            if (type == 1) {
                updateStr = { 'isLogin': isStoped };
            } else {
                updateStr = { 'isRegister': isStoped };
            }
            apiAdminUpdateRecord("limitIPModel", { _id: code }, updateStr, function () {
                var currentPage = $('#robotData').bootstrapTable('getOptions').pageNumber
                createList(currentPage);
                $.modal({ body: '修改成功' });
            });
        }
    });

}


$(document).ready(function () {

    $(function () {


        //数据表格初始化
        $('#robotData').bootstrapTable({
            striped: true, // 是否显示行间隔色
            pageNumber: 1, // 初始化加载第一页
            pagination: true, // 是否分页
            clickToSelect: true,
            theadClasses: "thead-light",//这里设置表头样式
            sidePagination: 'server', // server:服务器端分页|client：前端分页
            pageSize: 10, // 单页记录数
            pageList: [10, 20, 30],
            dataField: "recordArr",
            buttonsClass: 'light',
            buttonsPrefix: 'btn',
            totalField: "totalCount",
            showRefresh: false,// 刷新按钮
            onPageChange: function (number, size) {
                createList(number, size);
            },
            onPostBody: function () {
                //重新启用弹出层,否则formatter格式化函数返回的html字符串上的tooltip提示不生效
                $('[data-bs-toggle="tooltip"]').each(function (i, el) {
                    new bootstrap.Tooltip(el)
                })
            },
            onLoadSuccess: function () {
                //重新启用弹出层,否则formatter格式化函数返回的html字符串上的tooltip提示不生效
                $('[data-bs-toggle="tooltip"]').each(function (i, el) {
                    new bootstrap.Tooltip(el)
                })
            },
            queryParams: function (params) { // 上传服务器的参数
                var temp = {//如果是在服务器端实现分页，limit、offset这两个参数是必须的
                    limit: params.limit, // 每页显示数量
                    offset: params.offset, // SQL语句起始索引
                };
                return temp;
            },
            columns: [{
                checkbox: true,
                align: "center",
                valign: "middle",
            }, {
                title: 'id',
                field: '_id',
                visible: false
            },
            {
                title: '名称',
                width: 350,
                align: "center",
                valign: "middle",
                field: 'name',

            }, {
                title: 'IP地址',
                align: "center",
                valign: "middle",
                field: 'ip'
            }, {
                field: 'createTime',
                align: "center",
                valign: "middle",
                title: '创建时间',
                formatter: function (value) {
                    return new Date(value).toLocaleString();
                }
            },
            {
                title: '是否登录',
                align: "center",
                width: 50,
                valign: "middle",
                field: 'isLogin',
                formatter: function (value, row, index) {
                    var htm = "";
                    if (row.isLogin) {
                        htm = `<div id="switch1"  onClick='updateData("${row._id}",1,false)' class="simple-switch"><input type="checkbox" /> <span class="switch-handler"></span> </div>`;
                    } else {
                        htm = `<div id="switch1"  onClick='updateData("${row._id}",1,true)' class="simple-switch active"><input type="checkbox" /> <span class="switch-handler"></span> </div>`;
                    }
                    return htm;
                }
            },
            {
                title: '是否注册',
                width: 50,
                align: "center",
                valign: "middle",
                field: 'isRegister',
                formatter: function (value, row, index) {
                    var htm = "";
                    if (row.isRegister) {
                        htm = `<div id="switch1"  onClick='updateData( "${row._id}",2,false)' class="simple-switch"><input type="checkbox" /> <span class="switch-handler"></span> </div>`;
                    } else {
                        htm = `<div id="switch1"  onClick='updateData("${row._id}",2,true)' class="simple-switch active"><input type="checkbox" /> <span class="switch-handler"></span> </div>`;
                    }
                    return htm;
                }
            },
            {
                title: '操作',
                width: 250,
                align: "center",
                valign: "middle",
                formatter: option
            }]
        });
        createList();
    })




    function userBind(value, row, index) {
        var htm = "";
        if (value) {
            htm = `<h5><span class="badge badge-pill badge-success">已投放</span></h5>`;
        } else {
            htm = `<h5><span class="badge badge-pill badge-secondary">未投放</span></h5>`;
        }

        return htm;
    }

    // 定义删除、更新按钮
    function avaterImg(value, row, index) {
        var htm = "";
        htm = `<img  style="width: 40px ; height: 40px;"  src="${value}" class="img-thumbnail" >`;
        return htm;
    }

    // 定义删除、更新按钮
    function option(value, row, index) {
        var htm = "";
        htm = `<button type="button" class="btn btn-light"  data-bs-toggle="tooltip" data-bs-placement="top" data-bs-title="删除" onClick='deleteData("${row._id}")'><i class="bi bi-trash-fill fs-5 text-danger"></i></button>`;
        return htm;
    }

});


